package com.houduan.controller;

import com.houduan.dao.StatisticsDao;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

public class StatisticsServlet extends HttpServlet {

    private StatisticsDao statisticsDao;

    @Override
    public void init() throws ServletException {
        statisticsDao = new StatisticsDao();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        try {
            // 获取每日订单统计
            Map<String, Integer> dailyOrderCount = statisticsDao.getDailyOrderCount();
            Map<String, Double> dailyRevenue = statisticsDao.getDailyRevenue();

            // 将 dailyOrderCount 和 dailyRevenue 转换为有序列表
            List<String> orderLabels = new ArrayList<>(dailyOrderCount.keySet());
            List<Integer> orderData = new ArrayList<>(dailyOrderCount.values());
            List<String> revenueLabels = new ArrayList<>(dailyRevenue.keySet());
            List<Double> revenueData = new ArrayList<>(dailyRevenue.values());

            // 用户统计
            Map<String, Integer> userStatistics = statisticsDao.getUserStatistics();

            // 电脑使用统计
            Map<String, Object> computerUsageStats = statisticsDao.getComputerUsageStatistics();

            System.out.println("Order Labels: " + revenueLabels);
            System.out.println("Order Data: " + revenueData);

            // 设置 request 属性以供 JSP 页面使用
            request.setAttribute("orderLabels", orderLabels); // 直接使用日期作为标签
            request.setAttribute("orderData", orderData);
            request.setAttribute("revenueLabels", revenueLabels);
            request.setAttribute("revenueData", revenueData);
            request.setAttribute("totalUsers", userStatistics.getOrDefault("totalUsers", 0));
            request.setAttribute("activeUsers", userStatistics.getOrDefault("activeUsers", 0));
            request.setAttribute("newUsers", userStatistics.getOrDefault("newUsers", 0));
            request.setAttribute("totalHours", computerUsageStats.getOrDefault("totalUsage", 0));
            request.setAttribute("peakTime", computerUsageStats.getOrDefault("peakHour", "暂无数据"));

            // 转发到 JSP 页面
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.sendRedirect("error.jsp?message=加载统计数据失败");
        }
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
